<template>
	<view>
		<cu-custom :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">编辑资料</block>
		</cu-custom>
		<view class="cu-card article">
			<view class="cu-item">
				<form>
					<view class="cu-form-group padding-sm">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">背景:</view>
								<view v-if="requestStatus.upingBackSuccess&&!requestStatus.isUpingBack" @tap="ViewImage" :data-url="background" class="cu-avatar radius" :style="'background-image: url('+background+'?imageView2/2/w/200/h/200/q/75);'"></view>
								<view v-else @tap="ViewImage" :data-url="background" class="cu-avatar radius" :style="'background-image: url('+background+');'"></view>
								<view class="flex justify-start align-center">
									<view class="padding-left cu-load load-cuIcon" :class="requestStatus.isUpingBack?'loading':'over'"></view>
									<view v-if="requestStatus.isUpingBack">
										<text class="padding-left-xs text-grey text-sm">上传中</text>
									</view>
									<view v-else-if="requestStatus.isBackChanged">
										<text class="padding-left-xs text-grey text-sm">{{requestStatus.upingBackSuccess?'上传成功':'上传失败'}}</text>
									</view>
								</view>
							</view>
							<view @tap="ChooseBackgroundImage" class="action lines-grey flex justify-center align-center solid">
								<text class="cuIcon-camera text-grey padding-sm"></text>
							</view>
								
						</view>
					</view>
					<view class="cu-form-group padding-sm">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">头像:</view>
								<view v-if="requestStatus.upingAvatarSuccess&&!requestStatus.isUpingAvatar" @tap="ViewImage" :data-url="avatar" class="cu-avatar round" :style="'background-image: url('+avatar+'?imageView2/2/w/200/h/200/q/75);'"></view>
								<view v-else @tap="ViewImage" :data-url="avatar" class="cu-avatar round" :style="'background-image: url('+avatar+');'"></view>
								<view class="flex justify-start align-center">
									<view class="padding-left load-cuIcon" :class="requestStatus.isUpingAvatar?'loading':'over'"></view>
									<view v-if="requestStatus.isUpingAvatar">
										<text class="padding-left-xs text-grey text-sm">上传中</text>
									</view>
									<view v-else-if="requestStatus.isAvatarChanged">
										<text class="padding-left-xs text-grey text-sm">{{requestStatus.upingAvatarSuccess?'上传成功':'上传失败'}}</text>
									</view>
								</view>
							</view>
							<view @tap="ChooseAvatarImage" class="action lines-grey flex justify-center align-center solid">
								<text class="cuIcon-camera text-grey padding-sm"></text>
							</view>
						</view>
					</view>
					<view class="cu-form-group padding-sm">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">昵称:</view>
								<input maxlength="12" style="font-size: 26upx;" class="text-sm" placeholder="请输入昵称" v-model="nickname"></input>
							</view>		
							<text class="text-sm">{{nickname.length}}/12</text>
						</view>
					</view>
					<view class="cu-form-group padding-sm">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">分组:</view>
							</view>		
							<view v-if="userGroup!==null" class="flex justify-start align-center">
								<view @tap="chooseUserGroup" class="cu-tag radius line-blue text-cut">{{userGroup.name}}</view>
								<text @tap="clearUserGroupAction" class="cuIcon-close text-gray padding-left-xs"></text>
							</view>
							<button v-else @tap="chooseUserGroup"class="cu-btn bg-green radius sm">
								 选择分组
							</button>
						</view>
					</view>
					<view class="cu-form-group padding-sm">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">标签:</view>
							</view>		
							<view v-if="hobbyLabelCount>0" class="flex justify-start align-center">
								<view @tap="chooseHobbyLabel" class="cu-tag radius line-orange text-cut">已选择{{hobbyLabelCount}}项</view>
								<text @tap="clearHobbyLabels" class="cuIcon-close text-gray padding-left-xs"></text>
							</view>
							<button v-else @tap="chooseHobbyLabel" class="cu-btn bg-orange radius sm">
								 选择标签
							</button>
						</view>
					</view>
					<view v-if="userInfo.sex==-1" class="cu-form-group padding-sm">
						<view class="flex justify-between align-center" style="width: 100%;">
							<view class="flex justify-start align-center">
								<view class="label text-df padding-right">性别:</view>
								<text class="text-grey text-sm">(第一次更新后不可再修改)</text>
							</view>
							<button @tap="chooseSex" v-if="sexMale==1" style="transform: scale(0.85);" class="bg-blue cu-btn radius">
								<text class="cuIcon-male"></text>
							</button>
							<button @tap="chooseSex" v-if="sexMale==0" style="transform: scale(0.85);" class="bg-pink cu-btn radius">
								<text class="cuIcon-female"></text>
							</button>
							<button v-if="sexMale==-1" @tap="chooseSex" class="cu-btn bg-blue radius sm">
								 选择性别
							</button>
						</view>
					</view>
					<view class="cu-form-group padding-sm">
						<view class="flex justify-start align-center" style="width: 100%;">
							<view class="label text-df padding-right">来自:</view>
							<view class="flex justify-end align-center action" @tap="showPicker">
								<view class="flex justify-end align-center padding-right">
									<text class="text  wid27">{{text[0]}}</text>
									<image src="/static/images/index/icon_right.png" class="img30"></image>
								</view>
								<view class="flex justify-end align-center">
									<text class="text wid46">{{text[1]}}</text>
									<image src="/static/images/index/icon_down.png" class="img32"></image>
								</view>
							</view>
						</view>
					</view>
				</form>
			</view>
		</view>
		<view class="flex justify-center align-center padding">
			<button @tap="commitAction" :class="'cu-btn round '+themeColor" style="width: 80%;">确认提交</button>
		</view>
		<!--picker-view start-->
		<view v-if="cityData.length>0" class="tui-mask-screen" :class="[showPickerStatus?'tui-mask-show':'']" @tap="hidePicker"></view>
		<view v-if="cityData.length>0" class="tui-picker-box" :class="[showPickerStatus?'tui-pickerbox-show':'']">
			<view class="picker-header tui-list-item">
				<view class="btn-cancle" hover-class="tui-opcity" :hover-stay-time="150" @tap.stop="hidePicker">取消</view>
				<view class="btn-sure" hover-class="tui-opcity" :hover-stay-time="150" @tap.stop="picker">确定</view>
			</view>
			<picker-view indicator-style="height: 50px;" class="picker-view" :value="value" @change="columnPicker">
				<picker-view-column>
					<view v-for="(item,areaIndex) in areaArr" :key="areaIndex" class="item">{{item}}</view>
				</picker-view-column>
				<picker-view-column>
					<view v-for="(item,index) in countryArr" :key="index" class="item">{{item}}</view>
				</picker-view-column>
			</picker-view>
		</view>
		<!--picker-view end-->
	</view>
</template>

<script>
	import {updateUserInfo,uploadImage} from '@/api/api.js'
	import {getUserInfo} from '@/api/auth.js'
	import config from '@/api/config.js'
	const jianData = require('@/utils/jian.js')
	const pickerData = require('@/utils/picker.city.js')
	export default {
		data() {
			return {
				sexMale:-1,
				hobbyLabelCount:0,
				hobbyLabels:{},
				userGroup:null,
				themeColor:this.ThemeColor,
				cityData:null,
				background:'',
				areaArr: [],
				countryArr: [],
				value: [0, 0],
				iconHidden: true,
				showPickerStatus: false,
				text: ["请选择", "请选择"],
				nickname:'',
				avatar:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2F50%2Fv2-fce4f8a778fe3f24bca2cafc709b6847_hd.jpg&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619921092&t=e78e885bc59a9693f146f4993b2d7cfc',
				requestStatus:{
					isBackChanged:false,
					isUpingBack:false,
					upingBackSuccess:false,
					isAvatarChanged:false,
					isUpingAvatar:false,
					upingAvatarSuccess:false,
				}
			}
		},
		computed: {
			hasUpdateInfo() 
			{
				if(this.userInfo && this.userInfo.user_update_id !== null && this.userInfo.update_info !== null) 
				{
					return true
				}
				return false
			},
			userInfo() {
				return getUserInfo() 
			},
			uploadAvatarStatus() 
			{
				if(!this.isAvatarChanged) {
					return ''
				}
				if(this.isUpingAvatar) {
					return '上传中'
				}
				if(this.upingAvatarSuccess) {
					return '上传成功'
				}
				return '上传失败'
			},
			uploadBackStatus() 
			{
				if(!this.isBackChanged) {
					return ''
				}
				if(this.isUpingBack) {
					return '上传中'
				}
				if(this.upingBackSuccess) {
					return '上传成功'
				}
				return '上传失败'
			}
		},
		onLoad() {
			if(config.locationLevel == 1) {
				this.cityData = jianData
			}else{
				this.cityData = pickerData
			}
			if(this.userInfo.area !== null && this.userInfo.country !== null) {
				this.areaArr = this.toArr(this.cityData);
				let areaIndex = this.areaArr.indexOf(this.userInfo.area) !== -1? this.areaArr.indexOf(this.userInfo.area):0
				console.log('area index:'+areaIndex)
				this.countryArr = this.toArr(this.cityData[areaIndex].children);
				this.text = [this.userInfo.area,this.userInfo.country]
				let countryIndex = this.countryArr.indexOf(this.userInfo.country) !== -1? this.countryArr.indexOf(this.userInfo.country):0
				console.log('country index:'+countryIndex)
				this.value = [areaIndex,countryIndex]
				console.log(JSON.stringify(this.value))
			}else{
				this.areaArr = this.toArr(this.cityData);
				this.countryArr = this.toArr(this.cityData[0].children);
			}
			if(this.hasUpdateInfo) {
				if(this.userInfo.update_info.nickname && this.userInfo.update_info.nickname.length > 0) 
				{
					this.nickname = this.userInfo.update_info.nickname
				}else{
					this.nickname = this.userInfo.nickname
				}
				if(this.userInfo.update_info.avatar && this.userInfo.update_info.avatar.length > 0) 
				{
					this.avatar = this.userInfo.update_info.avatar
				}else{
					this.avatar = this.userInfo.avatar
				}
				if(this.userInfo.update_info.background && this.userInfo.update_info.background.length > 0) 
				{
					this.background = this.userInfo.update_info.background
				}else{
					this.background = this.userInfo.background
				}
			}else{
				if(this.userInfo !== null) {
					this.nickname = this.userInfo.nickname
					this.avatar = this.userInfo.avatar
					this.background = this.userInfo.background
					this.userGroup = this.userInfo.group
				}
			}
		},
		methods: {
			chooseSex() {
				let that = this
				uni.showActionSheet({
					itemList:[
						'女',
						'男'
					],
					success(res) {
						that.sexMale = res.tapIndex
					},
					fail(res) {
						console.log(res.errMsg)
					}
				})
			},
			clearHobbyLabels() 
			{
				this.hobbyLabels = {}
			},
			chooseHobbyLabel() 
			{
				let that = this
				uni.navigateTo({
					url:'/pages/lessuse/hobby-label-choose/hobby-label-choose',
					events:{
						finishChoose:function(res) {
							let count = 0
							Object.keys(res).forEach(key=>{
								count += res[key].length
							})
							that.hobbyLabelCount = count
							that.hobbyLabels = res
						}
					},
					success(res) {
						res.eventChannel.emit('didChoose',that.hobbyLabels)
					}
				})
			},
			clearUserGroupAction() 
			{
				this.userGroup = null
			},
			chooseUserGroup() 
			{
				let that = this
				uni.navigateTo({
					url:'/pages/lessuse/user-group-choose/user-group-choose',
					events:{
						finishChoose:function(res) {
							that.userGroup = res
						}
					}
				})
			},
			commitAction() 
			{
				//找出已经修改的内容
				let params = {}
				if(this.background && this.background !== this.userInfo.background && this.requestStatus.upingBackSuccess) {
					params['background'] = this.background
				}
				if(this.nickname && this.nickname !== this.userInfo.nickname) {
					params['nickname'] = this.nickname
				}
				if(this.avatar && this.avatar !== this.userInfo.avatar && this.requestStatus.upingAvatarSuccess) {
					params['avatar'] = this.avatar
				}
				let value = this.value;
				let area = this.cityData[value[0]].text;
				if(area && area.length > 0 && area !== 0 && area !== this.userInfo.area) {
					params['area'] = area
				}
				let country = this.cityData[value[0]].children[value[1]].text;
				if(country && country.length > 0 && country !== 0 && country !== this.userInfo.country) {
					params['country'] = country
				}
				if(this.userGroup !== null) {
					params['groupId'] = this.userGroup.group_id
				}else{
					params['groupId'] = 0
				}
				if(this.hobbyLabelCount>0) {
					//从每个分组里面选出第一个来进行组合，其余的再跟后
					let result = []
					Object.keys(this.hobbyLabels).forEach(key=>{
						let categoryList = this.hobbyLabels[key]
						if(categoryList.length > 0) {
							for(let index=0;index< 1;index++) {
								result.push(categoryList[index])
								continue
							}
						}
					})
					Object.keys(this.hobbyLabels).forEach(key=>{
						let categoryList = this.hobbyLabels[key]
						for(let index=1;index< categoryList.length;index++) {
							result.push(categoryList[index])
						}
					})
					params['hobbyLabels'] = result
				}
				if(this.sexMale !== -1) {
					params['sex'] = this.sexMale
				}
				uni.showLoading({
					title:'正在提交...'
				})
				updateUserInfo(params).then(res=>{
					uni.hideLoading()
					uni.navigateBack({
						delta:1
					})
					uni.showToast({
						title:'更新成功',
					})
					uni.$emit('UserInfoNeedUpdate')
				}).catch(error=>{
					uni.hideLoading()
				})
			},
			ChooseAvatarImage() {
				let this_ = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success: (res) => {
						let that_ = this_
						uni.navigateTo({
							url:'/pages/picture-cropper/picture-cropper?isAvatar=1&url='+res.tempFilePaths[0],
							events: {
							    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
							    imageCropperFinish: function(data) {
								  console.log(data.url)
							      that_.avatar = data.url
								  that_.requestStatus.isAvatarChanged = true
							      let timestamp = new Date().getTime()
							      let fileKey = String(timestamp)
								  let _that = that_
								  _that.requestStatus.isUpingAvatar = true
							      uploadImage(data.url, fileKey, (imgUrl) => {
							      	console.log(imgUrl)
							      	_that.avatar = imgUrl
									_that.requestStatus.upingAvatarSuccess = true
									_that.requestStatus.isUpingAvatar = false
							      }, (error)=>{
									  _that.requestStatus.upingAvatarSuccess = false
									  _that.requestStatus.isUpingAvatar = false
								  })
							    }
							}
						})
					}
				});
			},
			ChooseBackgroundImage() {
				let this_ = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success: (res) => {
						let that_ = this_
						uni.navigateTo({
							url:'/pages/picture-cropper/picture-cropper?isBackground=1&url='+res.tempFilePaths[0],
							events: {
							    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
							    imageCropperFinish: function(data) {
								  console.log(data.url)
							      that_.background = data.url
								  that_.requestStatus.isBackChanged = true
							      let timestamp = new Date().getTime()
							      let fileKey = String(timestamp)
								  let _that = that_
								  _that.requestStatus.isUpingBack = true
							      uploadImage(data.url, fileKey, (imgUrl) => {
							      	console.log(imgUrl)
							      	_that.background = imgUrl
									_that.requestStatus.isUpingBack = false
									_that.requestStatus.upingBackSuccess = true
							      }, (error)=>{
									 _that.requestStatus.isUpingBack = false
									 _that.requestStatus.upingBackSuccess = false 
								  })
							    }
							}
						})
					}
				});
			},
			ViewImage(e) {
				console.log(e.currentTarget.dataset.url)
				let currentUrl = e.currentTarget.dataset.url
				if(currentUrl == null || currentUrl.length == 0) {
					return
				}
				uni.previewImage({
					urls: [e.currentTarget.dataset.url],
					current: e.currentTarget.dataset.url
				});
			},
			toArr(object) {
				let arr = [];
				for (let i in object) {
					arr.push(object[i].text);
				}
				return arr;
			},
			//picker change切换事件
			columnPicker: function(e) {
				let value = e.detail.value;
				console.log(value)
				//如果两者下标不一致，表示滚动过
				if (this.value[0] !== value[0]) {
					this.areaArr = this.toArr(this.cityData);
					this.countryArr = this.toArr(this.cityData[value[0]].children);
					this.value = [value[0], 0]
				} else{
					this.value = value
				}
			},
			//确定按钮
			picker: function(e) {
				let value = this.value;
				if (this.cityData.length > 0) {
					let area = this.cityData[value[0]].text;
					let country = this.cityData[value[0]].children[value[1]].text;
					this.text = [area, country];
					this.showPickerStatus = false
				}
			},
			// 显示picker-view
			showPicker: function() {
				this.showPickerStatus = true
			},
			// 隐藏picker-view
			hidePicker: function() {
				this.showPickerStatus = false
			},
		}
	}
</script>

<style scoped>
	.label{
	   color: #777777;
	}
	/* picker start*/
	
	.tui-mask-screen {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 99996;
		transition: all 0.3s ease-in-out;
		opacity: 0;
		visibility: hidden;
	}
	
	.tui-mask-show {
		opacity: 1;
		visibility: visible;
	}
	
	.tui-picker-box {
		width: 100%;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 99999;
		visibility: hidden;
		transform: translate3d(0, 100%, 0);
		transform-origin: center;
		transition: all 0.3s ease-in-out;
		min-height: 20rpx;
		background: #fff;
	}
	
	.tui-pickerbox-show {
		transform: translate3d(0, 0, 0);
		visibility: visible;
	}
	
	.picker-header {
		width: 100%;
		height: 90rpx;
		padding: 0 46rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-sizing: border-box;
		font-size: 32rpx;
		background: #fff;
	}
	
	.tui-list-item::after {
		left: 0;
	}
	
	.btn-cancle {
		padding: 20rpx;
		color: #888;
	}
	
	.btn-sure {
		padding: 20rpx;
		color: #5677fc;
	}
	
	.picker-view {
		width: 100%;
		height: 260px;
	}
	
	.item {
		line-height: 50px;
		text-align: center;
	}
	
	/* picker end*/
	
	.search-box {
		width: 672rpx;
		border-radius: 10rpx;
		box-sizing: border-box;
		margin: 80rpx auto 40rpx auto;
		position: relative;
		/* #ifdef MP-ALIPAY */
		background: #fff;
		/* #endif */
	}
	
	.search-box::after {
		content: '';
		position: absolute;
		height: 200%;
		width: 200%;
		border: 1rpx solid #dbe1ef;
		transform-origin: 0 0;
		-webkit-transform-origin: 0 0;
		-webkit-transform: scale(0.5);
		transform: scale(0.5);
		left: 0;
		top: 0;
		border-radius: 20rpx;
		pointer-events: none;
	}
	
	.s-img {
		width: 34rpx;
		height: 34rpx;
		margin-right: 17rpx;
		flex-shrink: 0;
	}
	
	.input {
		font-size: 32rpx;
		color: #353535;
		width: 565rpx;
		padding-right: 5rpx;
		box-sizing: border-box;
		height: 100%;
	}
	
	.img30 {
		height: 30rpx;
		width: 30rpx;
	}
	
	.text {
		color: #353535;
		font-size: 28rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.wid27 {
		width: 100%;
	}
	
	.wid46 {
		width: 100%;
	}
	
	.img32 {
		height: 32rpx;
		width: 32rpx;
	}
	
	.pdr20 {
		padding-right: 20rpx;
	}
	
	.flr {
		margin-left: 10rpx;
	}
	
	.btn-select {
		padding: 20rpx 40rpx;
	}
</style>
